package com.chuangan.releasetask.Utils;
import com.alibaba.fastjson.JSONObject;
import com.chuangan.releasetask.pojo.User;
import io.jsonwebtoken.*;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/** jwt签证登录
 * @Author: jinLong
 * @Date: 2020/8/17 16:59
 * @Version 1.0
 */
@ConfigurationProperties("jwt.config")
@Component
public class JwtUtil {



    private String key ;
    private long ttl ;// 一个小时
    public String getKey() {
        return key;
    }
    public void setKey(String key) {
        this.key = key;
    }
    public long getTtl() {
        return ttl;
    }
    public void setTtl(long ttl) {
        this.ttl = ttl;
    }
    /**
     * * 生成 JWT
     @param id
      * @param subject
     * @return
     */
    public String createJWT(String id, String subject, User user) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
//        long exp = now + 1000*60*60*24;一天时间
        JwtBuilder builder = Jwts.builder().setId(id)
                .setSubject(subject)
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, key).claim("loginUser", user);
        if (ttl > 0) {
            builder.setExpiration( new Date( nowMillis + ttl));
        }
        return builder.compact();
    }
    /**
     * * 解析 JWT
     * @param jwtStr
     * @return
     */
    public Claims parseJWT(String jwtStr) {

        Claims   claims= Jwts.parser()
                    .setSigningKey(key)
                    .parseClaimsJws(jwtStr)
                    .getBody();

        return claims;
    }



    /**
     * 验证JWT
     *
     * @param jwtStr jwt字符串
     * @return JOSNObject 解析结果<br/>
     *         &emsp;&emsp;Success 成功标识<br/>
     *         &emsp;&emsp;&emsp;&emsp;true：成功<br/>
     *         &emsp;&emsp;&emsp;&emsp;false：失败<br/>
     *         &emsp;&emsp;Claim 声明对象<br/>
     *         &emsp;&emsp;ErrCode 错误码<br/>
     *         &emsp;&emsp;&emsp;&emsp;1005：过期<br/>
     *         &emsp;&emsp;&emsp;&emsp;1004：未登录
     */
    public JSONObject validateJWT(String jwtStr) {
        JSONObject pojo = new JSONObject();
        Claims claims = null;
        try {
            claims = parseJWT(jwtStr);
            pojo.put("Success", true);
            pojo.put("Claims", claims);
        } catch (ExpiredJwtException e) {
            pojo.put("Success", false);
            pojo.put("ErrCode", 1005);
            e.printStackTrace();
        } catch (Exception e) {
            pojo.put("Success", false);
            pojo.put("ErrCode", 1004);
            e.printStackTrace();
        }
        return pojo;
    }





}
